package com.maltys.tree;

import com.maltys.tree.base.TreeNode;

public class LowestCommonAncestor {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || root == p || root == q) {
            return root;
        }
        TreeNode leftSubTree = lowestCommonAncestor(root.left, p, q);
        TreeNode rightSubTree = lowestCommonAncestor(root.right, p, q);
        if (leftSubTree != null && rightSubTree != null) {
            return root;
        }
        if (leftSubTree == null && rightSubTree == null) {
            return null;
        }
        return leftSubTree == null ? rightSubTree : leftSubTree;
    }

}
